<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { reqAllRoleListAPT, reqAddOrUpdateRoleAPI, reqDeleteRoleAPI, reqAllMenuListAPI, reqAssignRoleAPI } from '@/apis/acl/role/index'
import type { RoleResponseData, Records, RoleData, MunuData } from '@/apis/acl/role/type'

//分页器当前页码
let pageNo = ref<number>(1)
//分页器每页数量
let pageSize = ref<number>(5)
//分页器数据总数
let total = ref<number>(0)
//控制对话框显示与隐藏
let dialogVisible = ref<boolean>(false)
//控制抽屉对话框显示与隐藏
let drawerVisible = ref<boolean>(false)
//对话框表单实例
let formRef = ref<any>()
//搜索职位的关键字
let keyWord = ref<string>('')
//收集接口返回的职位数据
let allRole = ref<Records>([])
//收集新增职位数据
let roleParmas = ref<RoleData>({
    roleName: '',
})
//封装挂载时请求职位接口
const getHasRole = async (paper = 1) => {
    pageNo.value = paper
    let result: RoleResponseData = await reqAllRoleListAPT(pageNo.value, pageSize.value, keyWord.value)
    if (result.code == 200) {
        allRole.value = result.data.records
        total.value = result.data.total
    }
}
onMounted(() => {
    getHasRole()
})
//分页器下拉框改变触发
const handleSizeChange = (val: number) => {
    getHasRole()
}
//点击搜索按钮
const findRole = async () => {
    getHasRole()
    keyWord.value = ''
}
//点击重置按钮
const resetRole = () => {
    keyWord.value = ''
    getHasRole()
}
//点击添加角色按钮
const addRole = () => {
    dialogVisible.value = true
    roleParmas.value.id = 0
    roleParmas.value.roleName = ''
    //清除表单上一次提示信息
    nextTick(() => {
        formRef.value.resetFields()
    })
}
//点击修改角色按钮
const updateRole = (row: RoleData) => {
    dialogVisible.value = true
    roleParmas.value = row
    //清除表单上一次提示信息
    nextTick(() => {
        formRef.value.resetFields()
    })
}
//drawer框实例
let treeRef = ref<any>()
//定义数组储存角色权限的接口数据
let menuArr = ref<MunuData[]>([])
//准备一个数组储存勾选的节点id数据
let selectArr = ref<number[]>([])
//点击分配角色按钮
const setRole = async (row: RoleData) => {
    drawerVisible.value = true
    roleParmas.value = row
    let result = await reqAllMenuListAPI((roleParmas.value.id as number))
    console.log(result);

    if (result.code == 200) {
        menuArr.value = result.data
        selectArr.value = filterSelectArr(menuArr.value, [])
    }
}
//递归过滤选中的节点
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }
    });
    return initArr
}
//点击drawer框的确定按钮
const hanler = async () => {
    //选中的节点
    let arr = treeRef.value.getCheckedKeys()
    //半选的节点
    let arr1 = treeRef.value.getHalfCheckedKeys()
    let result = await reqAssignRoleAPI((roleParmas.value.id as number), arr.concat(arr1))
    if (result.code === 200) {
        ElMessage.success('分配成功')
        drawerVisible.value = false
    } else {
        ElMessage.error('分配失败')
    }

}
//点击删除角色按钮
const deleteRole = async (row: RoleData) => {
    //点击删除按钮后，发送删除接口
    const result: any = await reqDeleteRoleAPI(row.id as number)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getHasRole(pageNo.value)
    } else {
        ElMessage.error('删除失败')
    }
}
//自定义效验规则
const validateRoleName = (rule: any, value: string, callback: any) => {
    if (!value || value.trim().length === 0) {
        callback(new Error('用户名不能为空'));
        return;
    }
    if (value.length < 2) {
        callback(new Error('长度至少2个字符'))
    } else {
        callback()
    }
}
//对话框表单效验
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validateRoleName },
    ]
}
//点击diaolog框的确定按钮
const addOrUpdateRole = async () => {
    await formRef.value.validate()
    const result = await reqAddOrUpdateRoleAPI(roleParmas.value)
    if (result.code === 200) {
        //提示
        ElMessage.success(roleParmas.value.id ? '修改成功' : '添加成功')
        //关闭对话框
        dialogVisible.value = false
        //重新获取数据
        getHasRole(roleParmas.value.id ? pageNo.value : 1)
    } else {
        ElMessage.error(roleParmas.value.id ? '修改失败' : '添加失败')
    }
}
</script>
<template>
    <el-card>
        <el-form class="form" inline>
            <el-form-item label="角色名称">
                <el-input v-model="keyWord" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyWord.trim().length === 0" @click="findRole">搜索</el-button>
                <el-button @click="resetRole">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card>
        <el-button type="primary" @click="addRole">添加角色</el-button>
        <!-- 表格 -->
        <el-table border :data="allRole">
            <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
            <el-table-column label="id" align="center" width="80" prop="id"></el-table-column>
            <el-table-column label="角色名称" align="center" prop="roleName"></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
            <el-table-column label="操作" align="center" width="400">
                <template #="{ row }">
                    <el-button type="primary" size="small" @click="setRole(row)">分配权限</el-button>
                    <el-button type="primary" size="small" @click="updateRole(row)">修改</el-button>
                    <el-button type="danger" size="small" @click="deleteRole(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination class="spu-pagination" :pager-count="5" background v-model:current-page="pageNo"
            v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]" layout="prev, pager, next, jumper, ->,sizes, total"
            :total="total" @current-change="getHasRole" @size-change="handleSizeChange">
        </el-pagination>
        <!-- 抽屉对话框 -->
        <el-drawer v-model="drawerVisible" direction="rtl">
            <template #header>
                <h1>分配权限</h1>
            </template>
            <template #default>
                <el-tree show-checkbox :data="menuArr" node-key="id" default-expand-all
                    :default-checked-keys="selectArr" :props="{ children: 'children', label: 'name' }" ref="treeRef">
                </el-tree>
            </template>
            <template #footer>
                <el-button type="primary" @click="hanler">确定</el-button>
                <el-button @click="drawerVisible = false">取消</el-button>
            </template>
        </el-drawer>
    </el-card>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" :title="roleParmas.id ? '修改角色' : '添加角色'">
        <el-form :model="roleParmas" :rules="rules" ref="formRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleParmas.roleName" placeholder="请输入角色名称"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="addOrUpdateRole">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
        </template>
    </el-dialog>
</template>
<style lang="scss" scoped>
.el-card {
    margin-bottom: 10px;
}

.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-table {
    margin: 10px 0;
}
</style>